package cn.zy.company.servlet.admin;



import cn.zy.company.entity.PageObj;
import cn.zy.company.entity.User;
import cn.zy.company.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/admin/showUser")
public class AdminShowUserServlet extends HttpServlet {
    PageObj<User> pageObj = new PageObj<User>();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String page = req.getParameter("page");
            String size = req.getParameter("size");
            if (page != null && page != "") {
                pageObj.setPage(Integer.parseInt(page));
            }
            if (size != null && size != "") {
                pageObj.setSize(Integer.valueOf(size));
            }
            UserService userService = new UserService();
            PageObj<User> all = userService.findAll(pageObj);
            req.setAttribute("dataList", all);
            req.getRequestDispatcher("/WEB-INF/jsp/admin/showUser.jsp").forward(req, resp);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String page = req.getParameter("page");
            String size = req.getParameter("size");
            if (page != null && page != "") {
                pageObj.setPage(Integer.parseInt(page));
            }
            if (size != null && size != "") {
                pageObj.setSize(Integer.valueOf(size));
            }
            String id = req.getParameter("id");
            UserService userService = new UserService();
            if (id != null && id != "") {
                User user = userService.findById(Integer.valueOf(id));
                List<User> list = new ArrayList<User>();
                list.add(user);
                pageObj.setList(list);
                req.setAttribute("dataList", pageObj);
                req.getRequestDispatcher("/WEB-INF/jsp/admin/showUser.jsp").forward(req, resp);
            }
            String name = req.getParameter("username");
            if (name != null && name != "") {
                PageObj<User> obj = userService.find(name, pageObj);
                req.setAttribute("dataList", obj);
                req.getRequestDispatcher("/WEB-INF/jsp/admin/showUser.jsp").forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
